<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
//获取字典标签
import { useDictStoreHook } from "@/store/modules/dict";
import { getDictLabel } from "@/utils/dict";
// 获取商品列表
import { getGoodsList } from "@/api/basicArchives/goods";
import { ImageViewer } from "@/components/common/ImageViewer";
import Delete from "@iconify-icons/ep/delete";
import EpSelect from "@iconify-icons/ep/select";

import { cloneDeep } from "@pureadmin/utils";
import { useColumns } from "../utils/columns";
const { directcolumns, directChildColumns } = useColumns();

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    depositoryType: undefined,
    depositoryId: undefined,
    itemList: [],
    stockStatus: 1
  }),
  supplierList: null,
  depositoryList: null
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

const deposlist = ref([]);
/**
 * 获取标签字典
 * 该函数首先检查本地存储中是否存在字典列表
 * 如果不存在，则从服务器获取字典列表，并将其存储在本地存储中
 * 然后，它根据指定的键（"PURCHASE_STATUS"）从字典列表中获取标签列表
 * 最后，它将一个包含所有标签的对象添加到标签列表的开头
 * @returns {Promise<void>} 当函数完成时解析的 Promise
 */
async function getTabDict() {
  const dictList = JSON.parse(localStorage.getItem("dictList")) || [];

  if (dictList.length > 0) {
    deposlist.value = getDictLabel(dictList, "DEPOSITORY_TYPE");
  } else {
    const params = {
      pageNum: 1,
      pageSize: 20
    };
    const { data } = await useDictStoreHook().getDictlist(params);
    deposlist.value = getDictLabel(data.records, "DEPOSITORY_TYPE");
  }
}

const searchValue = ref("");
const dataLoading = ref(false);
// 搜索商品
async function searchGoodsFun() {
  if (!searchValue.value) {
    newFormInline.value.itemList = [];
    return;
  }

  dataLoading.value = true;
  const params = {
    search: searchValue.value,
    goodsStatus: 1,
    pageNum: 1,
    pageSize: 30
  };
  const { data } = await getGoodsList(params);
  let tempList = data.records || [];
  tempList.forEach(v => {
    v.oriGoodsSpecList = cloneDeep(v.goodsSpecList);
  });
  newFormInline.value.itemList = tempList;
  dataLoading.value = false;
}
const chooseGoodsIds = ref([]);
const searchLoading = ref(false);
const searchGoodsList = ref([]);
const remoteMethod = async (searchKey: string) => {
  if (searchLoading.value) {
    return;
  }
  searchLoading.value = true;
  const params = {
    search: searchKey,
    goodsStatus: 1,
    pageNum: 1,
    pageSize: 20
  };
  const { data } = await getGoodsList(params);
  let tempList = data.records || [];
  tempList.forEach(v => {
    v.oriGoodsSpecList = cloneDeep(v.goodsSpecList);
  });
  searchGoodsList.value = tempList;
  setTimeout(() => {
    searchLoading.value = false;
  }, 200);
};

const selectList = computed(() => {
  let depositoryType = newFormInline.value.depositoryType;
  let tempList =
    depositoryType == 1 ? props.depositoryList : props.supplierList;
  return tempList;
});

const chooseGoodsChange = val => {
  let goodsId = val[0];
  let index = chooseGoodsIds.value.indexOf(goodsId);
  if (index == -1) {
    chooseGoodsIds.value.push(goodsId);
    let goods = searchGoodsList.value.find(v => v.id == goodsId);
    if (goods && goods.id) {
      newFormInline.value.itemList.push(goods);
    }
  } else {
    // 移除
    chooseGoodsIds.value.splice(index, 1);
    let findIndex = newFormInline.value.itemList.findIndex(
      v => v.id == goodsId
    );
    if (findIndex != -1) {
      newFormInline.value.itemList.splice(findIndex, 1);
    }
  }
};

const iconHide = ({ row }) => {
  if (row.oriGoodsSpecList.length == 0 || row.oriGoodsSpecList.length == 1) {
    return "icon-no";
  }
};

const handleDelete = (row, pIndex, index, flag) => {
  let isRemove = 0;
  if (flag == 1) {
    newFormInline.value.itemList.splice(index, 1);
    isRemove = 1;
  } else {
    // 删除规格 判断如果当前没有规格则把商品也进行删除
    row.goodsSpecList.splice(index, 1);
    if (row.goodsSpecList.length == 0) {
      newFormInline.value.itemList.splice(pIndex, 1);
      isRemove = 1;
    }
  }

  // 移除选中的商品id
  if (isRemove == 1) {
    let removeIndex = chooseGoodsIds.value.indexOf(row.id);
    if (removeIndex != -1) {
      chooseGoodsIds.value.splice(removeIndex, 1);
    }
  }
};

onMounted(() => {
  getTabDict();
});

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
  >
    <div class="text-black text-[15px] mb-4 ml-4 font-bold">入库信息</div>
    <el-row>
      <el-col :span="24" class="ml-10">
        <el-form-item label="入库类型" prop="depositoryType">
          <el-radio-group
            v-model="newFormInline.depositoryType"
            @change="newFormInline.depositoryId = null"
          >
            <el-radio
              v-for="item in deposlist"
              :key="item.itemValue"
              :value="Number(item.itemValue)"
            >
              {{ item.itemName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10" class="ml-10">
        <el-form-item label="入库仓库" prop="depositoryId">
          <el-select
            v-model="newFormInline.depositoryId"
            filterable
            placeholder="请选择"
            clearable
            class="!w-full"
          >
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="
                newFormInline.depositoryType == 1
                  ? item.depositoryName
                  : item.supplierName
              "
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <div class="text-black text-[15px] ml-4 font-bold">商品明细</div>
    <div class="b-content border">
      <el-row>
        <el-col :span="11">
          <el-form-item label="快速选择商品" prop="" label-width="auto">
            <!-- <el-input
              v-model.trim="searchValue"
              placeholder="输入商品编码/名称/规格编码后回车选择"
              clearable
              @change="searchGoodsFun"
            >
              <template #suffix>
                <el-icon class="el-input__icon">
                  <IconifyIconOffline
                    v-show="searchValue.length === 0"
                    icon="ri:search-line"
                  />
                </el-icon>
              </template>
            </el-input> -->
            <el-select
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="输入商品编码/名称/规格编码"
              :remote-method="remoteMethod"
              :loading="searchLoading"
              @change="chooseGoodsChange"
            >
              <el-option
                v-for="item in searchGoodsList"
                :key="item.id"
                :label="item.goodsName"
                :value="item.id"
                class="min-h-[60px]"
              >
                <div class="flex items-center justify-between py-2">
                  <div class="flex items-center">
                    <ImageViewer
                      width="45px"
                      height="45px"
                      radius="8px"
                      :src="item.imageJson"
                    />
                    <div class="ml-1">{{ item.goodsName }}</div>
                  </div>
                  <iconifyIconOffline
                    v-if="chooseGoodsIds.includes(item.id)"
                    class="text-blue-500 text-sm ml-2"
                    :icon="EpSelect"
                  />
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <pure-table
            ref="tableRef"
            row-key="id"
            align-whole="center"
            table-layout="auto"
            :loading="dataLoading"
            adaptive
            :adaptiveConfig="{ offsetBottom: 138 }"
            :data="newFormInline.itemList"
            :columns="directcolumns"
            :row-class-name="iconHide"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
          >
            <!-- 商品条码 -->
            <template #barCode="{ row }">
              <template
                v-if="
                  row.goodsSpecList &&
                  row.goodsSpecList.length == 1 &&
                  row.goodsSpecList[0].barCode
                "
              >
                <el-tooltip effect="dark" placement="top-start">
                  <template #content>
                    <div>主条码: {{ row.goodsSpecList[0].barCode }}</div>
                    <div>
                      辅助条码:
                      {{
                        row.goodsSpecList[0].auxiliaryBraCodeList &&
                        row.goodsSpecList[0].auxiliaryBraCodeList.length > 0
                          ? row.goodsSpecList[0].auxiliaryBraCodeList.join(", ")
                          : ""
                      }}
                    </div>
                  </template>
                  <div class="ml-[-10px] mr-[-10px]">
                    {{ row.goodsSpecList[0].barCode }}
                  </div>
                </el-tooltip>
              </template>
            </template>
            <!-- 删除 -->
            <template #operation="{ row, index }">
              <div class="flex justify-center">
                <iconifyIconOffline
                  class="text-red-500 text-lg cursor-pointer"
                  :icon="Delete"
                  @click="handleDelete(row, 0, index, 1)"
                />
              </div>
            </template>
            <!-- 子table -->
            <template #expand="{ row, index: pIndex }">
              <div class="ml-[36px]">
                <pure-table
                  row-key="id"
                  align-whole="center"
                  :data="row.goodsSpecList"
                  :columns="directChildColumns"
                  :show-header="false"
                  :header-cell-style="{
                    background: 'var(--el-fill-color-light)',
                    color: 'var(--el-text-color-primary)'
                  }"
                >
                  <!-- 规格名称 -->
                  <template #specName="scope">
                    <div class="flex items-center mr-[-12px]">
                      <ImageViewer
                        radius="8px"
                        :src="scope.row.specImageJson || row.imageJson"
                      />
                      <div
                        class="ml-[5px] cursor-pointer flex-1 overflow-hidden whitespace-normal"
                      >
                        {{ scope.row.specName }}
                      </div>
                    </div>
                  </template>
                  <!-- 规格编码 -->
                  <template #specCode="{ row }">
                    <el-tooltip
                      effect="dark"
                      :content="row.specCode"
                      placement="top-start"
                    >
                      <div class="text-cut">{{ row.specCode }}</div>
                    </el-tooltip>
                  </template>
                  <!-- 规格条码 -->
                  <template #barCode="{ row }">
                    <el-tooltip effect="dark" placement="top-start">
                      <template #content>
                        <div>主条码: {{ row.barCode }}</div>
                        <div>
                          辅助条码:
                          {{
                            row.auxiliaryBraCodeList &&
                            row.auxiliaryBraCodeList.length > 0
                              ? row.auxiliaryBraCodeList.join(", ")
                              : ""
                          }}
                        </div>
                      </template>
                      <div class="ml-[-10px] mr-[-10px]">
                        {{ row.barCode || "--" }}
                      </div>
                    </el-tooltip>
                  </template>
                  <!-- 删除 -->
                  <template #operation="{ index }">
                    <div class="flex justify-center">
                      <iconifyIconOffline
                        class="text-red-500 text-lg cursor-pointer"
                        :icon="Delete"
                        @click="handleDelete(row, pIndex, index, 2)"
                      />
                    </div>
                  </template>
                </pure-table>
              </div>
            </template>
          </pure-table>
        </el-col>
      </el-row>
    </div>
  </el-form>
</template>
<style lang="scss" scoped>
.b-content {
  margin: 15px 0 20px 40px;
}
.b-content.border {
  padding: 15px 15px 0;
  border: 1px solid #efefef;
  border-radius: 8px;
}
:deep(.icon-no .el-table__expand-icon) {
  display: none;
}
:deep(.el-table__expanded-cell) {
  padding: 0;
}
</style>
